<template>
  <div class="chat-container">
    <div class="chat-header" v-if="!joined">
      <h1>🎉 WebSocket 聊天室 🎉</h1>
      <div class="join-form">
        <div class="user-config">
          <input 
            v-model="tempUsername" 
            placeholder="输入昵称" 
            class="username-input"
            maxlength="20"
          />
          <span 
            class="user-emoji" 
            @click="openEmojiPicker = !openEmojiPicker"
          >
            {{ tempUserEmoji }}
          </span>
          <div v-if="openEmojiPicker" class="emoji-picker">
            <span 
              v-for="emoji in emojis" 
              :key="emoji" 
              @click="selectEmoji(emoji)"
              class="emoji-option"
            >
              {{ emoji }}
            </span>
          </div>
        </div>
        <button @click="joinChat" class="join-button">加入聊天室</button>
      </div>
    </div>

    <div class="chat-content" v-if="joined">
      <div class="online-count">在线人数: {{ onlineCount }}</div>
      
      <div class="message-list" ref="messageList">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          class="message"
          :class="{
            'system-message': message.type === 'system',
            'user-message': message.type === 'text',
            'join-message': message.type === 'join',
            'leave-message': message.type === 'leave'
          }"
        >
          <span class="message-sender" v-if="message.type === 'text'">
            {{ message.senderEmoji || '👤' }} {{ message.sender }}:
          </span>
          <span class="message-content">
            {{ message.text }}
            <span v-if="message.isHorn" class="audio-indicator">📢</span>
          </span>
          <span class="message-time">{{ formatTime(message.timestamp) }}</span>
        </div>
      </div>

      <div class="input-area">
        <div class="input-row">
          <input 
            v-model="newMessage" 
            @keyup.enter="sendMessage" 
            placeholder="输入消息..." 
            class="message-input"
          />
          <button @click="sendMessage" class="send-button">发送 ✉️</button>
          <button 
            @click="sendHorn" 
            class="horn-button"
            title="发送喇叭"
          >
            📢 喇叭
          </button>
        </div>
        <div class="emoji-controls">
          <span 
            v-for="emoji in quickEmojis" 
            :key="emoji" 
            @click="addEmojiToMessage(emoji)"
            class="quick-emoji"
            :title="`插入${emoji}`"
          >
            {{ emoji }}
          </span>
        </div>
      </div>
    </div>

    <audio ref="audioPlayer" :src="hornSound" style="display: none;"></audio>
  </div>
</template>

<script>
import hornSound from '/src/assets/horn.wav';

export default {
  data() {
    return {
      newMessage: '',
      messages: [],
      tempUsername: localStorage.getItem('chat-username') || `用户${Math.floor(Math.random() * 1000)}`,
      tempUserEmoji: localStorage.getItem('chat-emoji') || '👤',
      username: '',
      userEmoji: '',
      joined: false,
      openEmojiPicker: false,
      onlineCount: 1,
      hornSound: hornSound,
      emojis: ['😀', '😂', '😍', '🤔', '👍', '🎉', '❤️', '🔥', '✨', '💡'],
      quickEmojis: ['😊', '👍', '❤️', '🎶', '😂', '😎', '🎉','🤔','😭']
    }
  },
  methods: {
    joinChat() {
      if (this.tempUsername.trim() === '') {
        alert('请输入昵称');
        return;
      }
      
      this.username = this.tempUsername;
      this.userEmoji = this.tempUserEmoji;
      this.joined = true;
      
      localStorage.setItem('chat-username', this.username);
      localStorage.setItem('chat-emoji', this.userEmoji);
      
      const joinMessage = {
        type: 'join',
        sender: this.username,
        senderEmoji: this.userEmoji,
        timestamp: new Date().toISOString()
      };
      
      this.$socket.send(JSON.stringify(joinMessage));
      this.addSystemMessage(`欢迎 ${this.username} 加入聊天室`);
    },
    
    sendMessage() {
      if (this.newMessage.trim() === '') return;
      
      const message = {
        type: 'text',
        text: this.newMessage,
        sender: this.username,
        senderEmoji: this.userEmoji,
        timestamp: new Date().toISOString(),
        isHorn: false
      };
      
      this.$socket.send(JSON.stringify(message));
      this.newMessage = '';
      this.scrollToBottom();
    },
    
    sendHorn() {
      const message = {
        type: 'text',
        text: '发送了喇叭',
        sender: this.username,
        senderEmoji: this.userEmoji,
        timestamp: new Date().toISOString(),
        isHorn: true
      };
      
      this.$socket.send(JSON.stringify(message));
      this.playHorn();
      this.scrollToBottom();
    },
    
    playHorn() {
      const audioPlayer = this.$refs.audioPlayer;
      if (audioPlayer) {
        audioPlayer.currentTime = 0;
        audioPlayer.play().catch(e => {
          console.error('喇叭播放失败:', e);
        });
      }
    },
    
    addSystemMessage(text, type = 'system') {
      this.messages.push({
        type: type,
        text: text,
        timestamp: new Date().toISOString()
      });
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageList;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },
    
    selectEmoji(emoji) {
      this.tempUserEmoji = emoji;
      this.openEmojiPicker = false;
    },
    
    addEmojiToMessage(emoji) {
      this.newMessage += emoji;
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
  },
  mounted() {
    this.$options.sockets.onmessage = (data) => {
      try {
        const message = JSON.parse(data.data);
        
        if (message.isHorn && message.sender !== this.username) {
          this.playHorn();
          this.addSystemMessage(`${message.sender} 发送了喇叭`);
        } 
        else if (message.type === 'join') {
          this.onlineCount++;
          this.addSystemMessage(`${message.sender} 加入了聊天室`, 'join');
        }
        else if (message.type === 'leave') {
          this.onlineCount--;
          this.addSystemMessage(`${message.sender} 离开了聊天室`, 'leave');
        }
        else {
          this.messages.push(message);
        }
      } catch (e) {
        console.error('消息解析错误:', e);
      }
      this.scrollToBottom();
    };
  },
  beforeUnmount() {
    if (this.joined) {
      const leaveMessage = {
        type: 'leave',
        sender: this.username,
        timestamp: new Date().toISOString()
      };
      this.$socket.send(JSON.stringify(leaveMessage));
    }
  }
}
</script>

<style scoped>
/* 修改容器布局 */
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  height: 90vh; /* 限制整体高度 */
  display: flex;
  flex-direction: column;
}

/* 修改聊天内容区域布局 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 关键属性，允许内部滚动 */
}

/* 修改消息列表高度 */
.message-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0; /* 关键属性 */
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 确保输入区域不会被压缩 */
.input-area {
  flex-shrink: 0;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 以下是原有样式保持不变 */
.chat-header {
  text-align: center;
  margin: auto;
  width: 100%;
}

.chat-header h1 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 24px;
}

.join-form {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  margin: 0 auto;
}

.user-config {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.username-input {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border 0.3s;
}

.username-input:focus {
  outline: none;
  border-color: #42b983;
}

.user-emoji {
  font-size: 24px;
  cursor: pointer;
  transition: transform 0.2s;
  min-width: 32px;
  text-align: center;
}

.user-emoji:hover {
  transform: scale(1.2);
}

.emoji-picker {
  position: absolute;
  top: 50px;
  right: 0;
  background: white;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 100;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.emoji-option {
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.2s;
}

.emoji-option:hover {
  transform: scale(1.3);
}

.join-button {
  width: 100%;
  padding: 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.join-button:hover {
  background-color: #369f6b;
  transform: translateY(-2px);
}

.online-count {
  text-align: right;
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.message {
  padding: 8px 12px;
  margin-bottom: 12px;
  line-height: 1.5;
  position: relative;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(5px); }
  to { opacity: 1; transform: translateY(0); }
}

.user-message {
  background-color: #e3f2fd;
  border-left: 4px solid #42b983;
  border-radius: 8px;
  padding: 10px 15px;
}

.system-message,
.join-message,
.leave-message {
  padding: 5px;
  text-align: center;
  background: none;
  border: none;
}

.system-message {
  color: #666;
  font-style: italic;
  font-size: 0.9em;
}

.join-message {
  color: #2e7d32;
  font-weight: bold;
}

.leave-message {
  color: #c62828;
  font-weight: bold;
}

.message-sender {
  font-weight: bold;
  color: #2c3e50;
  margin-right: 5px;
}

.message-content {
  word-break: break-word;
}

.audio-indicator {
  margin-left: 5px;
  color: #ff9800;
}

.message-time {
  display: block;
  font-size: 0.75em;
  color: #7f8c8d;
  margin-top: 4px;
  text-align: right;
}

.input-row {
  display: flex;
  margin-bottom: 10px;
  gap: 10px;
}

.message-input {
  flex-grow: 1;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border 0.3s;
}

.message-input:focus {
  outline: none;
  border-color: #42b983;
}

.send-button, .horn-button {
  padding: 12px 20px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.send-button {
  background-color: #42b983;
  color: white;
}

.send-button:hover {
  background-color: #369f6b;
  transform: translateY(-1px);
}

.horn-button {
  background-color: #ffc107;
  color: #2c3e50;
}

.horn-button:hover {
  background-color: #ffab00;
  transform: translateY(-1px);
}

.emoji-controls {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-emoji {
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.2s;
}

.quick-emoji:hover {
  transform: scale(1.3);
}

@media (max-width: 768px) {
  .chat-container {
    margin: 10px;
    padding: 15px;
    height: 95vh;
  }
  
  .join-form {
    padding: 20px;
  }
  
  .input-row {
    flex-direction: column;
  }
  
  .send-button, .horn-button {
    width: 100%;
  }
}

.message-list::-webkit-scrollbar {
  width: 8px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>